package com.patMall.controller;

import com.github.pagehelper.Page;
import com.patMall.entity.Carousel;
import com.patMall.entity.User;
import com.patMall.service.CarouselService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 750909637@qq.com
 * @PackageName patMall
 * @Package com.patMall.controller
 * @Date 2024/1/10 11:49
 * @Version 1.0
 */
@Controller
@RequestMapping("carousel")
public class CarouselController {
    @Resource
    private CarouselService carouselService;
    @PostMapping("addCarousel")
    @ResponseBody
    public String addCarousel(Integer carouselId,@RequestParam(value = "file", required = false) MultipartFile uploadFile){
        Carousel updateCarousel = new Carousel();
        updateCarousel.setCarouselId(carouselId);
        updateCarousel.setIs_state(0);
        int update = carouselService.updateCarousel(updateCarousel);
        if (update == 1) {
            Carousel carousel = new Carousel();
            File file = new File("pat_mall/carousel/" + System.currentTimeMillis() + "_" + uploadFile.getOriginalFilename());
            System.out.println(file);
            try {
                uploadFile.transferTo(file);
                System.out.println("上传成功");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            carousel.setCarouselImg("/pat_mall/carousel/" + System.currentTimeMillis() + "_" + uploadFile.getOriginalFilename());
            int row = carouselService.addCarousel(carousel);
            if (row == 1) {
                return "success";
            }else{
                return "fail";
            }
        }else {
            return "NoFound";
        }
    }
    @PostMapping("getCarousel")
    @ResponseBody
    public Object getCarousel(){
        Map map = new HashMap();
        List<Carousel> carouselList = carouselService.getAllCarousel();
        System.err.println(carouselList);
        long count = carouselList.size();
        if (count >0){
            map.put("msg","success");
            map.put("count", count);
            map.put("data", carouselList);
        }else {
            map.put("msg","fail");
        }
        return map;
    }
}
